var express = require("express");
var router = express.Router();
var { webchatModel } = require("../db/webchat");
var { AdminModel } = require("../db/db");

var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hour = date.getHours();
var minute = date.getMinutes();
var formattedTime = year + '/' + month + '/' + day + ' ' + hour + ':' + minute;
// console.log(formattedTime);
// pc端获取聊天记录
router.post("/webchat", async (req, res) => {
    let filters = {}
    let users = [];
    const username = await AdminModel.find().where({
        _id: req.body.id,
    });
    if (req.body.id !== '') {
        filters.$or = [
            { toId: username[0]._id },
            { fromId: username[0]._id }
        ]
    }
    let data = await webchatModel.find(filters);
    data.forEach((item, index) => {
        if (users.includes(item.fromId)) { } else {
            if (item.fromId != username[0]._id) {
                users.push(item.fromId)
            }
        }
        if (users.includes(item.toId)) { } else {
            if (item.toId != username[0]._id) {
                users.push(item.toId)
            }
        }
    })
    res.send({
        data,
        users,
        username: username[0].username,
        mes: "获取成功"
    })
})
// uniapp端获取聊过天记录
router.post('/uniChat', async (req, res) => {
    let filters = {}
    let users = [];
    // let end_chat = [];
    if (req.body.id !== '') {
        filters.$or = [
            { toId: req.body.id },
            { fromId: req.body.id }
        ]
    }
    let data = await webchatModel.find(filters);
    // console.log(data);
    data.forEach((item, index) => {
        if (users.includes(item.fromId)) { } else {
            if (item.fromId != req.body.id) {
                // console.log('fromid', item);
                users.push(item.fromId)
                // end_chat.push({
                // })
            }
        }
        if (users.includes(item.toId)) { } else {
            if (item.toId != req.body.id) {
                // console.log('toid',item);
                users.push(item.toId)
            }
        }
    })
    let user_data = await AdminModel.where('_id').in(users)
    // console.log(user_data);
    res.send({
        user_data,
        code: 201
    })
})
// uniapp获取特定两人的聊天记录
router.post('/getChat', async (req, res) => {
    let data = await webchatModel.find({ $and: [{ toId: { $in: req.body.id } }, { fromId: { $in: req.body.id } }] })
    // console.log(data);
    res.send({
        data,
        code: 200
    })
})
// 添加聊天记录
router.post('/addWebchat', async (req, res) => {
    try {
        console.log(2345, req.body);
        await webchatModel.create(req.body);
        // let a = await AdminModel.find().where({
        //     _id: req.body.toId,
        // });
        // console.log(a[0]);
        // if (req.body.imageUrl) {
        //   console.log("发送的图片");
        //   a[0].end_chat = "[图片]";
        // } else {
        //   console.log("不是图片");
        //   a[0].end_chat = req.body.message;
        // }
        // a[0].end_date = formattedTime
        // await AdminModel.updateOne({ _id: req.body.id }, { $set: a[0] })
        res.send({ code: 200 }); // Return the newly created facility object
    } catch (err) {
        console.error('Failed to insert facility into MongoDB:', err);
        res.status(500).send({ error: 'Server error' });
    }
})
// 添加聊天记录
router.post('/addWebchatpc', async (req, res) => {
    try {
        console.log(2345, req.body);
        await webchatModel.create(req.body);
        let a = await AdminModel.find().where({
          _id: req.body.fromId,
        });
        console.log(a[0]);
        if (req.body.imageUrl) {
          console.log("发送的图片");
          a[0].end_chat = "[图片]";
        } else {
          console.log("不是图片");
          a[0].end_chat = req.body.message;
        }
        a[0].end_date = formattedTime
        await AdminModel.updateOne({ _id: req.body.id }, { $set: a[0] })
        res.send({ code: 200 }); // Return the newly created facility object
    } catch (err) {
        console.error('Failed to insert facility into MongoDB:', err);
        res.status(500).send({ error: 'Server error' });
    }
})

module.exports = router;